
<template>
  <div class="slaughter-container" style="max-width: 1200px; margin: 0 auto;">
    <!-- 基础信息 -->
    <div class="info-section">
      <div class="section-header">
        <span class="section-title">基础信息</span>
        <span class="edit-btn" @click="editSlaughterInfo">设置</span>
      </div>
      <div class="info-content">
        <div class="info-grid">
          <div class="info-item">
            <span class="label">批次：</span>
            <span class="value">{{ basicInfo.batchNumber }}</span>
          </div>
          <div class="info-item">
            <span class="label">到厂重量：</span>
            <span class="value">{{ basicInfo.arrivalWeight }}</span>
          </div>
          <div class="info-item">
            <span class="label">到厂时间：</span>
            <span class="value">{{ basicInfo.arrivalTime }}</span>
          </div>
          <div class="info-item">
            <span class="label">屠宰时间：</span>
            <span class="value">{{ basicInfo.slaughterTime }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 相关资质 -->
    <div class="info-section">
      <div class="section-header">
        <span class="section-title">相关资质</span>
      </div>
      <div class="certificate-content">
         <!-- 加载状态 -->
         <div v-if="certificateImagesLoading" class="certificate-loading">
           <div class="loading-spinner">⏳</div>
         </div>
         
         <!-- 已上传的图片 -->
         <div v-for="(image, index) in certificateImages" :key="index" class="certificate-item">
           <div class="certificate-preview">
             <img :src="image.url" :alt="`相关资质${index + 1}`" class="certificate-img">
             <div class="close-btn" @click="removeCertificateImage(index)">×</div>
        </div>
           <div class="certificate-label">相关资质</div>
        </div>

         <!-- 上传组件 -->
         <el-upload
           class="certificate-upload"
           action="http://localhost:34405/api/Image/upload-with-info"
           :show-file-list="false"
           :on-success="handleCertificateImageSuccess"
           :on-error="handleCertificateImageError"
           :on-progress="handleCertificateUploadProgress"
           :before-upload="beforeCertificateUpload"
           :data="getCertificateUploadData"
           name="file"
           accept="image/*"
           method="post"
           :headers="uploadHeaders"
         >
        <div class="add-certificate">
             <div class="add-btn" v-if="certificateUploadProgress === 0">
               <span class="plus-icon">+</span>
             </div>
             <div class="upload-progress-mini" v-else>
               <div class="progress-circle-mini">{{ certificateUploadProgress }}%</div>
        </div>
           </div>
         </el-upload>
      </div>
    </div>

    <!-- 企业信息 -->
    <div class="info-section">
      <div class="section-header">
        <span class="section-title">企业信息</span>
        <span class="edit-btn" @click="editCompanyInfo">设置</span>
      </div>
      <div class="info-content">
        <div class="info-item">
          <span class="label">公司名称：</span>
          <span class="value">{{ companyInfo.name }}</span>
        </div>
        <div class="info-item">
          <span class="label">成立时间：</span>
          <span class="value">{{ companyInfo.establishedDate }}</span>
        </div>
        <div class="info-item">
          <span class="label">公司地址：</span>
          <span class="value">{{ companyInfo.address }}</span>
        </div>
        <div class="info-item">
          <span class="label">公司简介：</span>
          <span class="value">{{ companyInfo.introduction }}</span>
        </div>
      </div>
    </div>

     <!-- 企业信息编辑对话框 -->
     <div v-if="showCompanyDialog" class="dialog-overlay" @click="closeCompanyDialog">
       <div class="dialog-content" @click.stop>
         <div class="dialog-header">
           <h3>企业信息</h3>
           <button class="close-button" @click="closeCompanyDialog">×</button>
         </div>
         <div class="dialog-body">
           <div class="form-row">
             <div class="form-label">
               <span class="required">*</span>公司名称：
             </div>
             <div class="form-input">
               <input type="text" v-model="companyDialogForm.name" placeholder="请输入公司名称" />
             </div>
           </div>
           <div class="form-row">
             <div class="form-label">
               <span class="required">*</span>公司地址：
             </div>
             <div class="form-input address-inputs">
               <select v-model="companyDialogForm.province" class="address-select">
                 <option value="">请选择省份</option>
                 <option value="四川省">四川省</option>
                 <option value="重庆市">重庆市</option>
                 <option value="北京市">北京市</option>
                 <option value="上海市">上海市</option>
                 <option value="广东省">广东省</option>
               </select>
               <select v-model="companyDialogForm.city" class="address-select">
                 <option value="">请选择城市</option>
                 <option value="巴中市">巴中市</option>
                 <option value="成都市">成都市</option>
                 <option value="绵阳市">绵阳市</option>
                 <option value="德阳市">德阳市</option>
               </select>
               <input type="text" v-model="companyDialogForm.district" placeholder="请输入区县" class="address-input" />
             </div>
           </div>
           <div class="form-row">
             <div class="form-label">
               <span class="required">*</span>成立时间：
             </div>
             <div class="form-input">
               <input type="date" v-model="companyDialogForm.establishedDate" />
             </div>
           </div>
           <div class="form-row">
             <div class="form-label">公司简介：</div>
             <div class="form-input">
               <textarea v-model="companyDialogForm.introduction" placeholder="请输入公司简介" rows="6"></textarea>
             </div>
           </div>
         </div>
         <div class="dialog-footer">
           <button class="cancel-button" @click="closeCompanyDialog">取消</button>
           <button class="save-button" @click="saveCompanyInfo">保存</button>
        </div>
      </div>
    </div>

    <!-- 企业照片 -->
    <div class="info-section">
      <div class="section-header">
        <span class="section-title">企业照片</span>
      </div>
      <div class="photos-content">
         <!-- 加载状态 -->
         <div v-if="photoImagesLoading" class="photo-loading">
           <div class="loading-spinner">⏳</div>
         </div>
         
         <!-- 已上传的图片 -->
         <div v-for="(image, index) in photoImages" :key="index" class="photo-item">
           <div class="photo-preview">
             <img :src="image.url" :alt="`企业照片${index + 1}`" class="photo-img">
             <div class="close-btn" @click="removePhotoImage(index)">×</div>
           </div>
         </div>

         <!-- 上传组件 -->
         <el-upload
           class="photo-upload"
           action="http://localhost:34405/api/Image/upload-with-info"
           :show-file-list="false"
           :on-success="handlePhotoImageSuccess"
           :on-error="handlePhotoImageError"
           :on-progress="handlePhotoUploadProgress"
           :before-upload="beforePhotoUpload"
           :data="getPhotoUploadData"
           name="file"
           accept="image/*"
           method="post"
           :headers="uploadHeaders"
         >
           <div class="add-photo">
             <div class="add-btn" v-if="photoUploadProgress === 0">
               <span class="plus-icon">+</span>
             </div>
             <div class="upload-progress-mini" v-else>
               <div class="progress-circle-mini">{{ photoUploadProgress }}%</div>
             </div>
           </div>
         </el-upload>
       </div>
     </div>

    <!-- 屠宰信息对话框 -->
    <div v-if="showSlaughterDialog" class="dialog-overlay" @click="closeSlaughterDialog">
      <div class="dialog-content" @click.stop>
        <div class="dialog-header">
          <h3>屠宰信息设置</h3>
          <button class="close-button" @click="closeSlaughterDialog">×</button>
        </div>
        <div class="dialog-body">
          <div class="form-row">
            <div class="form-label">
              <span class="required">*</span>批次号：
            </div>
            <div class="form-input">
              <input type="text" v-model="slaughterDialogForm.batchNumber" readonly class="form-input-readonly" />
            </div>
          </div>

          <div class="form-row">
            <div class="form-label">
              <span class="required">*</span>平均重量：
            </div>
            <div class="form-input">
              <input type="number" v-model="slaughterDialogForm.averageWeight" placeholder="请输入平均重量" min="0" step="0.1" />
            </div>
          </div>

          <div class="form-row">
            <div class="form-label">
              <span class="required">*</span>到厂时间：
            </div>
            <div class="form-input">
              <input type="datetime-local" v-model="slaughterDialogForm.arrivalTime" />
            </div>
          </div>

          <div class="form-row">
            <div class="form-label">
              <span class="required">*</span>屠宰时间：
            </div>
            <div class="form-input">
              <input type="datetime-local" v-model="slaughterDialogForm.slaughterTime" />
            </div>
          </div>
        </div>
        <div class="dialog-footer">
          <button class="cancel-button" @click="closeSlaughterDialog">取消</button>
          <button class="save-button" @click="saveSlaughterInfo">保存</button>
        </div>
      </div>
    </div>
  </div>
</template>
  
  <script setup lang="ts">
import { ref, reactive, defineProps, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { apiWreit } from '@/Ulter/AxiosHepler'

// 定义props
const props = defineProps<{
  batchNumber: string
}>()

// 基础信息数据
const basicInfo = reactive({
  batchNumber: '20210718',
  arrivalWeight: '20公斤',
  arrivalTime: '2021年10月18日 18:32:21',
  slaughterTime: '2021年10月19日 10:30:20'
})

// 企业信息数据
const companyInfo = reactive({
  name: '四川祥瑞食品有限公司',
  establishedDate: '2016年7月18日',
  address: '四川省巴中市通江县XXX',
  introduction: '企业简介企业简介企业简介企业简介企业简介企业简介企业简介企业简介企业简介企业简介企业简介企业简介企业简介企业简介企业简介企业简介企业简介企业简介企业简介企业简介企业简介企业简介企业简介企业简介企业简介企业简介企业简介企业简介企业简介企业简介企业简介企业简介'
})

// 屠宰信息对话框相关
const showSlaughterDialog = ref(false)
         const slaughterDialogForm = reactive({
           batchNumber: '',
           averageWeight: 0,
           arrivalTime: '',
           slaughterTime: ''
         })

// 企业信息对话框相关
const showCompanyDialog = ref(false)
const companyDialogForm = reactive({
  name: '',
  province: '',
  city: '',
  district: '',
  establishedDate: '',
  introduction: ''
})

// 相关资质图片相关变量
const certificateImages = ref<Array<{url: string, imageBatch: string, traceStage: string, traceType: string}>>([])
const certificateImagesLoading = ref(false)
const certificateUploadProgress = ref(0)

// 企业照片相关变量
const photoImages = ref<Array<{url: string, imageBatch: string, traceStage: string, traceType: string}>>([])
const photoImagesLoading = ref(false)
const photoUploadProgress = ref(0)

// 上传请求头
const uploadHeaders = {
  'Authorization': `Bearer ${localStorage.getItem('token') || ''}`
}

// 功能函数
const editSlaughterInfo = () => {
  console.log('编辑屠宰信息，批次号:', props.batchNumber)
  // 填充表单数据
             slaughterDialogForm.batchNumber = props.batchNumber
           slaughterDialogForm.averageWeight = parseFloat(basicInfo.arrivalWeight.replace('公斤', '')) || 0
           slaughterDialogForm.arrivalTime = formatDateTimeForInput(basicInfo.arrivalTime)
           slaughterDialogForm.slaughterTime = formatDateTimeForInput(basicInfo.slaughterTime)
  
  showSlaughterDialog.value = true
}

const closeSlaughterDialog = () => {
  showSlaughterDialog.value = false
}

const saveSlaughterInfo = async () => {
  try {
    // 验证必填字段
    if (!slaughterDialogForm.averageWeight || !slaughterDialogForm.arrivalTime || !slaughterDialogForm.slaughterTime) {
      ElMessage.error('请填写所有必填字段')
      return
    }

    console.log('准备保存屠宰信息:', {
      batchNumber: slaughterDialogForm.batchNumber,
      averageWeight: slaughterDialogForm.averageWeight,
      arrivalTime: slaughterDialogForm.arrivalTime,
      slaughterTime: slaughterDialogForm.slaughterTime
    })

    // 调用API保存数据
    const response = await apiWreit.post('/api/SlaughterInfo', {
      batchNumber: slaughterDialogForm.batchNumber,
      averageWeight: slaughterDialogForm.averageWeight,
      arrivalTime: slaughterDialogForm.arrivalTime,
      slaughterTime: slaughterDialogForm.slaughterTime
    })

    console.log('保存屠宰信息API响应:', response)

    if (response.status === 200) {
      ElMessage.success('屠宰信息保存成功')
      closeSlaughterDialog()
      
      // 重新获取数据以确保显示最新信息
      if (props.batchNumber) {
        await getSlaughterInfo()
      }
    } else {
      ElMessage.error('保存失败')
    }
  } catch (error: any) {
    console.error('保存屠宰信息失败:', error)
    if (error.response) {
      console.error('API响应错误:', error.response.data)
      ElMessage.error(`保存失败: ${error.response.data?.message || '未知错误'}`)
    } else {
      ElMessage.error('网络连接失败，请检查网络状态')
    }
  }
}

// 获取屠宰信息
const getSlaughterInfo = async () => {
  try {
    console.log('正在获取批次号为', props.batchNumber, '的屠宰信息...')
    
    const response = await apiWreit.get(`/api/SlaughterInfo/search?batchNumber=${props.batchNumber}`)
    
    if (response.status === 200 && response.data) {
      const result = response.data
      console.log('屠宰信息API响应:', result)
      
      if (result.code === 300 && result.data && result.data.length > 0) {
        const data = result.data[0] // 取第一条记录
        console.log('获取到屠宰信息数据:', data)
        
        // 更新基础信息
        basicInfo.batchNumber = data.batchNumber || props.batchNumber
        basicInfo.arrivalWeight = data.averageWeight ? `${data.averageWeight}公斤` : '20公斤'
        basicInfo.arrivalTime = data.arrivalTime ? formatDateTimeForDisplay(data.arrivalTime) : '2021年10月18日 18:32:21'
        basicInfo.slaughterTime = data.slaughterTime ? formatDateTimeForDisplay(data.slaughterTime) : '2021年10月19日 10:30:20'
        
        console.log('屠宰信息更新成功:', {
          batchNumber: basicInfo.batchNumber,
          arrivalWeight: basicInfo.arrivalWeight,
          arrivalTime: basicInfo.arrivalTime,
          slaughterTime: basicInfo.slaughterTime
        })
      } else {
        console.log('未找到屠宰信息数据或响应格式异常:', result)
        // 保持默认值
      }
    } else {
      console.warn('屠宰信息API响应异常:', response)
    }
  } catch (error: any) {
    console.error('获取屠宰信息失败:', error)
    if (error.response?.status === 404) {
      console.log('未找到对应的屠宰信息')
    } else {
      console.error('网络错误或其他错误:', error.message)
    }
  }
}

// 加载屠宰信息
const loadSlaughterInfo = () => {
  if (props.batchNumber) {
    console.log('开始加载屠宰信息，批次号:', props.batchNumber)
    getSlaughterInfo()
  } else {
    console.warn('批次号为空，无法加载屠宰信息')
  }
}

// 时间格式化函数
const formatDateTimeForInput = (dateTimeStr: string) => {
  // 将 "2021年10月18日 18:32:21" 格式转换为 "2021-10-18T18:32"
  const match = dateTimeStr.match(/(\d{4})年(\d{1,2})月(\d{1,2})日 (\d{1,2}):(\d{1,2}):(\d{1,2})/)
  if (match) {
    const [, year, month, day, hour, minute] = match
    return `${year}-${month.padStart(2, '0')}-${day.padStart(2, '0')}T${hour.padStart(2, '0')}:${minute.padStart(2, '0')}`
  }
  return ''
}

const formatDateTimeForDisplay = (dateTimeStr: string) => {
  // 将 "2021-10-18T18:32" 格式转换为 "2021年10月18日 18:32:21"
  const date = new Date(dateTimeStr)
  if (!isNaN(date.getTime())) {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()
    return `${year}年${month}月${day}日 ${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}:${second.toString().padStart(2, '0')}`
  }
  return dateTimeStr
}

const addCertificate = () => {
  console.log('添加证书')
}

const addPhoto = () => {
  console.log('添加照片')
}

const editCompanyInfo = () => {
  console.log('编辑企业信息，批次号:', props.batchNumber)
  // 填充表单数据
  companyDialogForm.name = companyInfo.name
  companyDialogForm.province = '四川省'
  companyDialogForm.city = '巴中市'
  companyDialogForm.district = '通江县 XXX'
  companyDialogForm.establishedDate = formatDateForInput(companyInfo.establishedDate)
  companyDialogForm.introduction = companyInfo.introduction
  
  showCompanyDialog.value = true
}

const closeCompanyDialog = () => {
  showCompanyDialog.value = false
}

const saveCompanyInfo = async () => {
  try {
    // 验证必填字段
    if (!companyDialogForm.name || !companyDialogForm.province || !companyDialogForm.city || !companyDialogForm.establishedDate) {
      ElMessage.error('请填写所有必填字段')
      return
    }

    // 构建完整地址
    const fullAddress = `${companyDialogForm.province}${companyDialogForm.city}${companyDialogForm.district}`

    // 调用API保存数据
    const response = await apiWreit.post('/api/SlaughterCompany/AddOrUpdate', {
      batchNumber: props.batchNumber,
      companyName: companyDialogForm.name,
      companyAddress: fullAddress,
      establishedDate: companyDialogForm.establishedDate,
      introduction: companyDialogForm.introduction
    })

    if (response.data.success) {
      ElMessage.success('企业信息保存成功')
      // 更新本地数据
      companyInfo.name = companyDialogForm.name
      companyInfo.address = fullAddress
      companyInfo.establishedDate = formatDateForDisplay(companyDialogForm.establishedDate)
      companyInfo.introduction = companyDialogForm.introduction
      closeCompanyDialog()
    } else {
      ElMessage.error(response.data.message || '保存失败')
    }
  } catch (error) {
    console.error('保存企业信息失败:', error)
    ElMessage.error('保存失败，请重试')
  }
}

// 获取企业信息
const getCompanyInfo = async () => {
  try {
    const response = await apiWreit.get(`/api/SlaughterCompany/GetByBatch/${props.batchNumber}`)
    if (response.data.success && response.data.data) {
      const data = response.data.data
      companyInfo.name = data.companyName || '四川锦祥食品有限公司'
      companyInfo.address = data.companyAddress || '四川省巴中市通江县XXX'
      companyInfo.establishedDate = data.establishedDate ? formatDateForDisplay(data.establishedDate) : '2016年7月18日'
      companyInfo.introduction = data.introduction || '企业简介企业简介企业简介企业简介企业简介企业简介企业简介企业简介企业简介企业简介企业简介企业简介企业简介企业简介企业简介企业简介企业简介企业简介企业简介企业简介企业简介企业简介企业简介企业简介企业简介企业简介企业简介企业简介企业简介企业简介企业简介企业简介'
    }
  } catch (error) {
    console.error('获取企业信息失败:', error)
  }
}

// 加载企业信息
const loadCompanyInfo = () => {
  if (props.batchNumber) {
    getCompanyInfo()
  }
}

// 日期格式化函数
const formatDateForInput = (dateStr: string) => {
  // 将 "2016年7月18日" 格式转换为 "2016-07-18"
  const match = dateStr.match(/(\d{4})年(\d{1,2})月(\d{1,2})日/)
  if (match) {
    const [, year, month, day] = match
    return `${year}-${month.padStart(2, '0')}-${day.padStart(2, '0')}`
  }
  return ''
}

const formatDateForDisplay = (dateStr: string) => {
  // 将 "2016-07-18" 格式转换为 "2016年7月18日"
  const date = new Date(dateStr)
  if (!isNaN(date.getTime())) {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    return `${year}年${month}月${day}日`
  }
  return dateStr
}

// 图片处理相关函数
const getFullImageUrl = (imagePath: string) => {
  if (!imagePath) return ''
  if (imagePath.startsWith('http')) return imagePath
  return `http://localhost:34405${imagePath}`
}

// 相关资质图片上传相关方法
const getCertificateUploadData = () => {
  const traceStage = '相关资质'
  const traceType = `屠宰信息_${traceStage}`
  console.log('相关资质上传数据 - traceStage:', traceStage)
  console.log('相关资质上传数据 - traceType:', traceType)
  return {
    imageBatch: props.batchNumber || '',
    traceStage: traceStage,
    traceType: traceType
  }
}

const beforeCertificateUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  const isLt5M = file.size / 1024 / 1024 < 5
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!')
    return false
  }
  certificateUploadProgress.value = 0
  return true
}

const handleCertificateImageSuccess = (response: any) => {
  console.log('相关资质图片上传响应:', response)
  if (response && response.data) {
    const imageData = response.data
    const fullImageUrl = getFullImageUrl(imageData.imagePath)
    const traceStage = '相关资质'
    const traceType = `屠宰信息_${traceStage}`
    certificateImages.value.push({
      url: fullImageUrl,
      imageBatch: imageData.imageBatch || props.batchNumber || '',
      traceStage: imageData.traceStage || traceStage,
      traceType: imageData.traceType || traceType
    })
    console.log('相关资质图片上传成功:', {
      url: fullImageUrl,
      batch: imageData.imageBatch,
      stage: imageData.traceStage,
      type: imageData.traceType
    })
    certificateUploadProgress.value = 0
    ElMessage.success('相关资质上传成功!')
  } else {
    console.error('相关资质上传失败，响应格式异常:', response)
    ElMessage.error('上传失败，未返回图片地址')
  }
}

const handleCertificateUploadProgress = (event: any) => {
  certificateUploadProgress.value = Math.round(event.percent)
}

const handleCertificateImageError = (error: any) => {
  console.error('相关资质图片上传失败:', error)
  certificateUploadProgress.value = 0
  ElMessage.error('相关资质上传失败，请重试')
}

const removeCertificateImage = async (index: number) => {
  try {
    const imageToDelete = certificateImages.value[index]
    if (!imageToDelete || !imageToDelete.url) {
      ElMessage.error('图片信息不完整，无法删除')
      return
    }

    // 从完整URL中提取imagePath
    let imagePath = imageToDelete.url
    if (imagePath.startsWith('http://localhost:34405')) {
      imagePath = imagePath.replace('http://localhost:34405', '')
    }

    console.log('准备删除相关资质图片:', {
      index: index,
      imagePath: imagePath,
      fullUrl: imageToDelete.url
    })

    // 调用删除API
    const response = await apiWreit.delete('/api/Image/delete-by-path', {
      params: {
        imagePath: imagePath
      },
      headers: {
        'Accept': 'text/plain'
      }
    })

    console.log('删除相关资质图片API响应:', response)

    if (response.status === 200) {
      // 从本地数组中移除图片
      certificateImages.value.splice(index, 1)
      ElMessage.success('相关资质图片删除成功')
      console.log('相关资质图片删除成功，已从本地列表移除')
    } else {
      throw new Error('删除失败')
    }
  } catch (error: any) {
    console.error('删除相关资质图片失败:', error)
    if (error.response) {
      console.error('API响应错误:', error.response.data)
      ElMessage.error(`删除失败: ${error.response.data?.message || '未知错误'}`)
    } else {
      ElMessage.error('网络连接失败，请检查网络状态')
    }
  }
}

// 加载相关资质图片
const loadCertificateImages = async () => {
  if (!props.batchNumber) {
    console.warn('批次号为空，无法查询相关资质图片')
    return
  }
  certificateImagesLoading.value = true
  try {
    const traceStage = '相关资质'
    const traceType = `屠宰信息_${traceStage}`
    console.log('🔍 开始查询相关资质图片:')
    console.log('  - 批次号:', props.batchNumber)
    console.log('  - traceStage:', traceStage)
    console.log('  - traceType:', traceType)
    const response = await apiWreit.get('/api/Image/GetByCondition', {
      params: {
        imageBatch: props.batchNumber,
        traceStage: traceStage,
        traceType: traceType
      }
    })
    if (response.status === 200 && response.data) {
      const images = response.data.data || response.data || []
      const processedImages = images.map((image: any) => ({
        url: getFullImageUrl(image.imagePath),
        imageBatch: image.imageBatch || props.batchNumber,
        traceStage: image.traceStage || traceStage,
        traceType: image.traceType || traceType
      }))
      certificateImages.value = processedImages
      console.log('✅ 相关资质图片查询成功:', processedImages.length, '张图片')
      console.log('图片列表:', processedImages)
      if (processedImages.length === 0) {
        console.log('📝 暂无相关资质图片')
      }
    } else {
      console.warn('查询相关资质图片响应异常:', response)
      certificateImages.value = []
    }
  } catch (error: any) {
    console.error('❌ 查询相关资质图片失败:', error)
    certificateImages.value = []
    if (error.response?.status === 404) {
      console.log('📝 未找到对应的相关资质图片')
    } else {
      ElMessage.error('查询相关资质图片失败')
    }
  } finally {
    certificateImagesLoading.value = false
  }
}

// 企业照片图片上传相关方法
const getPhotoUploadData = () => {
  const traceStage = '企业照片'
  const traceType = `屠宰信息_${traceStage}`
  console.log('企业照片上传数据 - traceStage:', traceStage)
  console.log('企业照片上传数据 - traceType:', traceType)
  return {
    imageBatch: props.batchNumber || '',
    traceStage: traceStage,
    traceType: traceType
  }
}

const beforePhotoUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  const isLt5M = file.size / 1024 / 1024 < 5
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!')
    return false
  }
  photoUploadProgress.value = 0
  return true
}

const handlePhotoImageSuccess = (response: any) => {
  console.log('企业照片图片上传响应:', response)
  if (response && response.data) {
    const imageData = response.data
    const fullImageUrl = getFullImageUrl(imageData.imagePath)
    const traceStage = '企业照片'
    const traceType = `屠宰信息_${traceStage}`
    photoImages.value.push({
      url: fullImageUrl,
      imageBatch: imageData.imageBatch || props.batchNumber || '',
      traceStage: imageData.traceStage || traceStage,
      traceType: imageData.traceType || traceType
    })
    console.log('企业照片图片上传成功:', {
      url: fullImageUrl,
      batch: imageData.imageBatch,
      stage: imageData.traceStage,
      type: imageData.traceType
    })
    photoUploadProgress.value = 0
    ElMessage.success('企业照片上传成功!')
  } else {
    console.error('企业照片上传失败，响应格式异常:', response)
    ElMessage.error('上传失败，未返回图片地址')
  }
}

const handlePhotoUploadProgress = (event: any) => {
  photoUploadProgress.value = Math.round(event.percent)
}

const handlePhotoImageError = (error: any) => {
  console.error('企业照片图片上传失败:', error)
  photoUploadProgress.value = 0
  ElMessage.error('企业照片上传失败，请重试')
}

const removePhotoImage = async (index: number) => {
  try {
    const imageToDelete = photoImages.value[index]
    if (!imageToDelete || !imageToDelete.url) {
      ElMessage.error('图片信息不完整，无法删除')
      return
    }

    // 从完整URL中提取imagePath
    let imagePath = imageToDelete.url
    if (imagePath.startsWith('http://localhost:34405')) {
      imagePath = imagePath.replace('http://localhost:34405', '')
    }

    console.log('准备删除企业照片图片:', {
      index: index,
      imagePath: imagePath,
      fullUrl: imageToDelete.url
    })

    // 调用删除API
    const response = await apiWreit.delete('/api/Image/delete-by-path', {
      params: {
        imagePath: imagePath
      },
      headers: {
        'Accept': 'text/plain'
      }
    })

    console.log('删除企业照片图片API响应:', response)

    if (response.status === 200) {
      // 从本地数组中移除图片
      photoImages.value.splice(index, 1)
      ElMessage.success('企业照片图片删除成功')
      console.log('企业照片图片删除成功，已从本地列表移除')
    } else {
      throw new Error('删除失败')
    }
  } catch (error: any) {
    console.error('删除企业照片图片失败:', error)
    if (error.response) {
      console.error('API响应错误:', error.response.data)
      ElMessage.error(`删除失败: ${error.response.data?.message || '未知错误'}`)
    } else {
      ElMessage.error('网络连接失败，请检查网络状态')
    }
  }
}

// 加载企业照片图片
const loadPhotoImages = async () => {
  if (!props.batchNumber) {
    console.warn('批次号为空，无法查询企业照片图片')
    return
  }
  photoImagesLoading.value = true
  try {
    const traceStage = '企业照片'
    const traceType = `屠宰信息_${traceStage}`
    console.log('🔍 开始查询企业照片图片:')
    console.log('  - 批次号:', props.batchNumber)
    console.log('  - traceStage:', traceStage)
    console.log('  - traceType:', traceType)
    const response = await apiWreit.get('/api/Image/GetByCondition', {
      params: {
        imageBatch: props.batchNumber,
        traceStage: traceStage,
        traceType: traceType
      }
    })
    if (response.status === 200 && response.data) {
      const images = response.data.data || response.data || []
      const processedImages = images.map((image: any) => ({
        url: getFullImageUrl(image.imagePath),
        imageBatch: image.imageBatch || props.batchNumber,
        traceStage: image.traceStage || traceStage,
        traceType: image.traceType || traceType
      }))
      photoImages.value = processedImages
      console.log('✅ 企业照片图片查询成功:', processedImages.length, '张图片')
      console.log('图片列表:', processedImages)
      if (processedImages.length === 0) {
        console.log('📝 暂无企业照片图片')
      }
    } else {
      console.warn('查询企业照片图片响应异常:', response)
      photoImages.value = []
    }
  } catch (error: any) {
    console.error('❌ 查询企业照片图片失败:', error)
    photoImages.value = []
    if (error.response?.status === 404) {
      console.log('📝 未找到对应的企业照片图片')
    } else {
      ElMessage.error('查询企业照片图片失败')
    }
  } finally {
    photoImagesLoading.value = false
  }
}

// 监听批次号变化，自动加载数据
watch(() => props.batchNumber, (newBatchNumber) => {
  if (newBatchNumber) {
    console.log('批次号变化，重新加载数据:', newBatchNumber)
    loadSlaughterInfo()
    loadCompanyInfo()
    loadCertificateImages()
    loadPhotoImages()
  }
}, { immediate: true })

// 组件挂载时加载数据
onMounted(() => {
  loadSlaughterInfo()
  loadCompanyInfo()
  loadCertificateImages()
  loadPhotoImages()
})
</script>
  
  <style scoped>
.slaughter-container {
  display: flex;
  flex-direction: column;
  gap: 6px;
  padding: 10px;
  background-color: #ffffff;
  min-height: 100vh;
}

.info-section {
  padding: 10px 0;
  flex: 1;
  min-width: 300px;
  width: 100%;
  margin-bottom: 6px;
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 6px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  color: #1890ff;
}

.edit-btn {
  color: #1890ff;
  cursor: pointer;
  font-size: 14px;
  border: 1px solid #1890ff;
  padding: 2px 8px;
  border-radius: 4px;
}

.info-content {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 6px;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.label {
  font-weight: 500;
  color: #666;
  font-size: 14px;
}

.value {
  color: #333;
  font-size: 14px;
  line-height: 1.5;
}

.certificate-content,
.photos-content {
  display: flex;
  gap: 6px;
  flex-wrap: wrap;
  margin-top: 6px;
}

.certificate-item,
.photo-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100px;
  height: 120px;
}

.certificate-img,
.photo-img {
  width: 100%;
  height: 100px;
  object-fit: contain;
}

.certificate-label {
  font-size: 12px;
  color: #666;
  margin-top: 4px;
}

.add-certificate,
.add-photo {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.add-btn {
  width: 100px;
  height: 100px;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: #999;
  cursor: pointer;
  background-color: #f5f5f5;
}

.add-btn:hover {
  background-color: #e8e8e8;
}

/* 对话框样式 */
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.dialog-content {
  background-color: white;
  border-radius: 8px;
  width: 90%;
  max-width: 500px;
  max-height: 80vh;
  overflow-y: auto;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 20px 0 20px;
  border-bottom: 1px solid #e8e8e8;
  padding-bottom: 15px;
}

.dialog-header h3 {
  margin: 0;
  color: #333;
  font-size: 18px;
  font-weight: 600;
}

.close-button {
  background: none;
  border: none;
  font-size: 24px;
  color: #999;
  cursor: pointer;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: background-color 0.2s;
}

.close-button:hover {
  background-color: #f5f5f5;
  color: #666;
}

.dialog-body {
  padding: 20px;
}

.form-row {
  margin-bottom: 20px;
}

.form-label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #333;
  font-size: 14px;
}

.required {
  color: #ff4d4f;
  margin-right: 4px;
}

.form-input {
  width: 100%;
}

.form-input input,
.form-input textarea {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  font-size: 14px;
  transition: border-color 0.2s;
  box-sizing: border-box;
}

.form-input input:focus,
.form-input textarea:focus {
  outline: none;
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.1);
}

.form-input-readonly {
  background-color: #f5f5f5;
  color: #666;
  cursor: not-allowed;
}

.form-input textarea {
  resize: vertical;
  min-height: 80px;
  font-family: inherit;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 0 20px 20px 20px;
  border-top: 1px solid #e8e8e8;
  padding-top: 15px;
}

.cancel-button,
.save-button {
  padding: 8px 20px;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
  border: 1px solid;
  transition: all 0.2s;
}

.cancel-button {
  background-color: white;
  border-color: #d9d9d9;
  color: #666;
}

.cancel-button:hover {
  border-color: #1890ff;
  color: #1890ff;
}

.save-button {
  background-color: #1890ff;
  border-color: #1890ff;
  color: white;
}

.save-button:hover {
  background-color: #40a9ff;
  border-color: #40a9ff;
}

.save-button:active {
  background-color: #096dd9;
  border-color: #096dd9;
}

/* 图片上传和显示相关样式 */
.certificate-preview,
.photo-preview {
  position: relative;
  width: 100%;
  height: 100px;
  border-radius: 4px;
  overflow: hidden;
}

.certificate-preview img,
.photo-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.close-btn {
  position: absolute;
  top: 2px;
  right: 2px;
  width: 20px;
  height: 20px;
  background-color: rgba(255, 0, 0, 0.8);
  color: white;
  border: none;
  border-radius: 50%;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: bold;
  transition: background-color 0.2s;
}

.close-btn:hover {
  background-color: rgba(255, 0, 0, 1);
}

.certificate-loading,
.photo-loading {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100px;
  height: 100px;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  background-color: #f5f5f5;
}

.loading-spinner {
  font-size: 20px;
  color: #999;
}

.plus-icon {
  font-size: 24px;
  color: #999;
  font-weight: bold;
}

.upload-progress-mini {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
}

.progress-circle-mini {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #1890ff;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: bold;
}

.certificate-upload,
.photo-upload {
  display: inline-block;
}

.certificate-upload .el-upload,
.photo-upload .el-upload {
  display: block;
}

/* 地址选择器样式 */
.address-inputs {
  display: flex;
  gap: 8px;
  align-items: center;
}

.address-select {
  flex: 1;
  padding: 10px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  font-size: 14px;
  background-color: white;
  transition: border-color 0.2s;
}

.address-select:focus {
  outline: none;
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.1);
}

.address-input {
  flex: 1;
  padding: 10px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  font-size: 14px;
  transition: border-color 0.2s;
}

.address-input:focus {
  outline: none;
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.1);
}
</style>